<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/22
 * Time: 9:10
 */

namespace common\business\file;

use common\consts\CommonResources;
use common\consts\Consts;
use common\helpers\StringUtil;
use common\models\File;
use Yii;
use common\business\task\TaskResponseData;
use yii\helpers\Json;
use yii\web\UploadedFile;

class FileHelper
{
    /**
     * @param $file UploadedFile
     * @param $path string
     * @param $task_type string
     * @param $allowExtensions array
     * @return TaskResponseData
     */
    public static function upload($file, $path, $allowExtensions = [], $task_type = null){
        if (!$file){
            $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File','File not found');
            return new TaskResponseData(TaskResponseData::CODE_ERROR, $errMsg);
        }
        // 目录不存在则创建
        if (!is_dir($path)) {
            if (!mkdir($path)) {
                $failReason = CommonResources::ACTION_NAME_MODEL_FAIL('Create', 'Folder', $path);
                $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File', $failReason);
                Yii::error($errMsg);
                return new TaskResponseData(TaskResponseData::CODE_ERROR, $errMsg);
            }
        }

        if (count($allowExtensions) > 0){
            $isFileExtensionAllowed = false;
            foreach ($allowExtensions as $allowExtension){
                if (strtolower($file->extension) == strtolower($allowExtension)){
                    $isFileExtensionAllowed = true;
                    break;
                }
            }
            if (!$isFileExtensionAllowed){
                $failReason = 'Only Support '.implode(Consts::SEPARATOR, $allowExtensions).' File Formats';
                $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File', $failReason);
                return new TaskResponseData(TaskResponseData::CODE_ERROR, $errMsg);
            }
        }

        if ($file->hasError) {
            $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File','File has error');
            return  new TaskResponseData(TaskResponseData::CODE_ERROR, $errMsg);
        }

//        $fileName = $file->name;
//        $fileName4check = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);

//        由于PHPExcel读取中文名文件不行，只能用英文名称
        $uid = uniqid();
        $fileName = md5($file->baseName . '-' . $uid) . '.' . $file->extension;

//        if (file_exists($path . $fileName4check)) {
//            $fileName = $file->baseName.'_'.$uid.'.' . $file->extension;
//        }

//        $fileName4save = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $fileName);

        if (!$file->saveAs($path . $fileName)){
            $failReason = CommonResources::ACTION_NAME_MODEL_FAIL('Save', 'File', $file->baseName);
            $errMsg = CommonResources::ACTION_FAIL_MSG('Upload', 'File',$failReason);
            return  new TaskResponseData(TaskResponseData::CODE_ERROR, $errMsg);
        }

        $fileModel = new File();
        $fileModel->file_name = $fileName;
        $fileModel->file_base_name = $file->baseName;
        $fileModel->file_extension = $file->extension;
        $fileModel->file_path = $path;
        $fileModel->file_fullname = $fileModel->file_path.$fileModel->file_name;
        $fileModel->file_uid = $uid;
        if (!StringUtil::isNullOrWhiteSpace($task_type)){
            $fileModel->file_task_type = $task_type;
        }

        if (!$fileModel->save()) {
            $failReason = Json::encode($fileModel->getErrors());
            return new TaskResponseData(TaskResponseData::CODE_ERROR, CommonResources::ACTION_NAME_MODEL_FAIL('Upload & Saved', 'File', $fileName, $failReason), $fileName);
        }

        return new TaskResponseData(TaskResponseData::CODE_SUCCESS, CommonResources::ACTION_NAME_MODEL_SUCCESS('Upload & Saved', 'File', $fileName), $fileName);
    }
}